//
//  APIManager.m
//  OCStarterProject
//
//  Created by huaya on 2025/10/2.
//

#import "APIManager.h"
#import <AFNetworking/AFNetworking.h>
#import "APIURLManager.h"
#import "APIResponse.h"

// 请求超时时间
static NSTimeInterval const kRequestTimeoutInterval = 30.0;

// 响应状态码定义
static NSInteger const kSuccessStatusCode = 200;
static NSInteger const kUnauthorizedStatusCode = 401;
static NSInteger const kForbiddenStatusCode = 403;
static NSInteger const kTokenExpiredStatusCode = 1003;
static NSInteger const kInsufficientBalanceStatusCode = 900;

@interface APIManager ()

@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
@property (nonatomic, strong) NSMutableDictionary *customHeaders;

@end

@implementation APIManager

#pragma mark - 单例实现

+ (instancetype)sharedInstance {
    static APIManager *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[self alloc] init];
    });
    return sharedManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupSessionManager];
        _customHeaders = [NSMutableDictionary dictionary];
        [self configureDefaultHeaders];
    }
    return self;
}

#pragma mark - 配置管理

- (void)setupSessionManager {
    _sessionManager = [AFHTTPSessionManager manager];
    
    // 安全策略配置
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    _sessionManager.securityPolicy = securityPolicy;
    
    // 请求序列化器
    _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    [_sessionManager.requestSerializer setTimeoutInterval:kRequestTimeoutInterval];
    
    // 响应序列化器
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:
                                                @"text/html",
                                                @"application/json",
                                                @"text/json",
                                                @"text/javascript",
                                                @"text/plain",
                                                @"application/javascript",
                                                @"video/mpeg",
                                                @"video/mp4", nil];
    _sessionManager.responseSerializer = responseSerializer;
}

- (void)configureDefaultHeaders {
    [self.customHeaders setObject:@"application/json;charset=UTF-8"            forKey:@"Content-Type"];
    [self.customHeaders setObject:[MKDeviceUtils appBundleShortVersion]        forKey:@"app_v"];       //客户端版本号
    [self.customHeaders setObject:[MKDeviceUtils appBundleVersion]             forKey:@"app_b_v"];     //客户端内部版本号 int
    [self.customHeaders setObject:@"iOS"                                       forKey:@"os"];          //系统
    [self.customHeaders setObject:[MKDeviceUtils systemVersionString]          forKey:@"os_v"];        //系统版本
    [self.customHeaders setObject:[MKDeviceUtils deviceType]                   forKey:@"os_name"];     //设备名称
    [self.customHeaders setObject:@([NSDate mk_currentTimestamp]).stringValue  forKey:@"timestamp"];   //时间戳
    [self.customHeaders setObject:@"application/json" forKey:@"Content-Type"];
    [self.customHeaders setObject:@"application/json" forKey:@"Accept"];
}

#pragma mark - 公共请求方法

+ (NSURLSessionDataTask *)sendPostRequest:(NSString *)url
                               parameters:(NSDictionary *)params
                                    model:(Class)modelClass
                                  success:(RequestSuccessHandler)successBlock
                                  failure:(RequestFailureHandler)failureBlock {
    return [self sendPostRequest:url
                      parameters:params
                           model:modelClass
                 completionQueue:dispatch_get_main_queue()
                         success:successBlock
                         failure:failureBlock];
}

+ (NSURLSessionDataTask *)sendQuickPostRequest:(NSString *)url
                                    parameters:(NSDictionary *)params
                                         model:(Class)modelClass
                                       success:(QuickRequestSuccessHandler)successBlock
                                       failure:(RequestFailureHandler)failureBlock {
    // 缓存功能暂不实现，保持与TL_NetworkRequestManger相同的接口
    return [self sendPostRequest:url
                      parameters:params
                           model:modelClass
                         success:^(BOOL success, id responseData, id requestModel) {
        if (successBlock) {
            successBlock(success, responseData, NO, requestModel);
        }
    } failure:failureBlock];
}

+ (NSURLSessionDataTask *)sendPostRequest:(NSString *)url
                               parameters:(NSDictionary *)params
                                    model:(Class)modelClass
                          completionQueue:(dispatch_queue_t)queue
                                  success:(RequestSuccessHandler)successBlock
                                  failure:(RequestFailureHandler)failureBlock {
    
    // 检查网络连接
//    if (![self isNetworkAvailable]) {
//        if (failureBlock) {
//            failureBlock(nil, [NSError errorWithDomain:@"NetworkError" code:-1009 userInfo:@{NSLocalizedDescriptionKey: @"网络连接不可用"}]);
//        }
//        return nil;
//    }
    
    // 构建完整URL
    NSString *fullURL = url;
    
    APIManager *manager = [self sharedInstance];
    [manager applyCustomHeaders];
    
    // 设置授权头
    NSString *userToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"userToken"];
    if (userToken && userToken.length > 0) {
        NSString *authHeader = [NSString stringWithFormat:@"Bfkyou %@", userToken];
        [manager.sessionManager.requestSerializer setValue:authHeader forHTTPHeaderField:@"Authorization"];
    }else{
        [manager.sessionManager.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
    }
    
    manager.sessionManager.completionQueue = queue;
    
    NSLog(@"🌐 POST请求URL: %@", fullURL);
    NSLog(@"📤 请求参数: %@", params ?: @{});
    
    return [manager.sessionManager POST:fullURL
                             parameters:params
                                headers:nil
                               progress:nil
                                success:^(NSURLSessionDataTask *task, id responseObject) {
        [self handleSuccessResponse:responseObject
                               task:task
                              model:modelClass
                            success:successBlock];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self handleFailureResponse:task error:error failure:failureBlock];
    }];
}

+ (NSURLSessionDataTask *)sendGetRequest:(NSString *)url
                              parameters:(NSDictionary *)params
                                   model:(Class)modelClass
                                 success:(RequestSuccessHandler)successBlock
                                 failure:(RequestFailureHandler)failureBlock {
    return [self sendGetRequest:url
                     parameters:params
                          model:modelClass
                completionQueue:dispatch_get_main_queue()
                        success:successBlock
                        failure:failureBlock];
}

+ (NSURLSessionDataTask *)sendGetRequest:(NSString *)url
                              parameters:(NSDictionary *)params
                                   model:(Class)modelClass
                         completionQueue:(dispatch_queue_t)queue
                                 success:(RequestSuccessHandler)successBlock
                                 failure:(RequestFailureHandler)failureBlock {
    
//    if (![self isNetworkAvailable]) {
//        if (failureBlock) {
//            failureBlock(nil, [NSError errorWithDomain:@"NetworkError" code:-1009 userInfo:@{NSLocalizedDescriptionKey: @"网络连接不可用"}]);
//        }
//        return nil;
//    }
    
    NSString *fullURL = url;
    
    APIManager *manager = [self sharedInstance];
    [manager applyCustomHeaders];
    
    NSString *userToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"userToken"];
    if (userToken && userToken.length > 0) {
        NSString *authHeader = [NSString stringWithFormat:@"Bfkyou %@", userToken];
        [manager.sessionManager.requestSerializer setValue:authHeader forHTTPHeaderField:@"Authorization"];
    }else{
        [manager.sessionManager.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
    }
    
    manager.sessionManager.completionQueue = queue;
    
    NSLog(@"🌐 GET请求URL: %@", fullURL);
    NSLog(@"📤 请求参数: %@", params ?: @{});
    
    return [manager.sessionManager GET:fullURL
                            parameters:params
                               headers:nil
                              progress:nil
                               success:^(NSURLSessionDataTask *task, id responseObject) {
        [self handleSuccessResponse:responseObject
                               task:task
                              model:modelClass
                            success:successBlock];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self handleFailureResponse:task error:error failure:failureBlock];
    }];
}

#pragma mark - 响应处理

+ (void)handleSuccessResponse:(id)responseObject
                         task:(NSURLSessionDataTask *)task
                        model:(Class)modelClass
                      success:(RequestSuccessHandler)successBlock {
    
    NSLog(@"✅ 请求成功，响应数据: %@", responseObject);
    
    APIResponse *responseModel = [[APIResponse alloc] init];
    
    if ([responseObject isKindOfClass:[NSDictionary class]]) {
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        
        // 解析状态码
        NSNumber *code = responseDict[@"code"];
        responseModel.code = code ? [code integerValue] : kSuccessStatusCode;
        responseModel.message = responseDict[@"msg"] ?: (responseDict[@"message"] ?:@"");
        responseModel.data = responseDict[@"data"] ?: responseDict;
        
        // 处理特殊状态码
        [self handleSpecialStatusCode:responseModel.code];
        
        // 数据模型转换
        id resultData = responseModel.data;
        if (modelClass && [resultData isKindOfClass:[NSDictionary class]]) {
            // 这里可以集成MJExtension或其他模型转换库
             resultData = [modelClass modelWithDictionary:resultData];
        }
        
        BOOL isSuccess = (responseModel.code == kSuccessStatusCode);
        
        if (successBlock) {
            successBlock(isSuccess, resultData, responseModel);
        }
    } else {
        responseModel.code = -1;
        responseModel.message = @"响应数据格式错误";
        
        if (successBlock) {
            successBlock(NO, responseObject, responseModel);
        }
    }
}

+ (void)handleFailureResponse:(NSURLSessionDataTask *)task
                        error:(NSError *)error
                      failure:(RequestFailureHandler)failureBlock {
    
    NSLog(@"❌ 请求失败: %@", error.localizedDescription);
    
    // 取消请求不回调失败
    if (error.code != -999 && failureBlock) {
        failureBlock(task, error);
    }
}

+ (void)handleSpecialStatusCode:(NSInteger)statusCode {
    switch (statusCode) {
        case kUnauthorizedStatusCode:
        case kTokenExpiredStatusCode:
            // 处理未授权或token过期
            [self handleAuthorizationFailure];
            break;
            
        case kInsufficientBalanceStatusCode:
            // 处理余额不足
            [self handleInsufficientBalance];
            break;
            
        default:
            break;
    }
}

+ (void)handleAuthorizationFailure {
    // 跳转登录页面
    [TL_LoginViewController presentLoginView:nil];
    
    // 清除用户token
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userToken"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (void)handleInsufficientBalance {
    // 处理余额不足逻辑
    [[NSNotificationCenter defaultCenter] postNotificationName:@"UserInsufficientBalanceNotification" object:nil];
}

#pragma mark - 工具方法

- (void)applyCustomHeaders {
    for (NSString *field in self.customHeaders) {
        [self.sessionManager.requestSerializer setValue:self.customHeaders[field] forHTTPHeaderField:field];
    }
}

+ (void)setRequestHeaderValue:(NSString *)value forField:(NSString *)field {
    APIManager *manager = [self sharedInstance];
    if (value) {
        manager.customHeaders[field] = value;
    } else {
        [manager.customHeaders removeObjectForKey:field];
    }
}

+ (void)cancelAllNetworkRequests {
    APIManager *manager = [self sharedInstance];
    [manager.sessionManager.session getTasksWithCompletionHandler:^(NSArray<NSURLSessionDataTask *> *dataTasks, NSArray<NSURLSessionUploadTask *> *uploadTasks, NSArray<NSURLSessionDownloadTask *> *downloadTasks) {
        for (NSURLSessionTask *task in dataTasks) {
            [task cancel];
        }
        for (NSURLSessionTask *task in uploadTasks) {
            [task cancel];
        }
        for (NSURLSessionTask *task in downloadTasks) {
            [task cancel];
        }
    }];
}

+ (BOOL)isNetworkAvailable {
    return [AFNetworkReachabilityManager sharedManager].reachable;
}

@end
